package Network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//UDP的回显客户端
public class UdpEchoClient {
    //1.创建DatagramSocket对象
    private DatagramSocket datagramSocket = null;
    private String serverIp;
    private int serverPort;
    //2.创建构造函数
    public UdpEchoClient(String ip,int port) throws SocketException {
        datagramSocket = new DatagramSocket();//客户端的端口系统自动分配
        this.serverIp = ip;
        this.serverPort = port;
    }
    //3.创建start函数，开启客户端，从控制台发出请求，发送给服务器，接收服务器的响应，显示到屏幕上
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动");
        while (true){
            System.out.print("->");
            String request = scanner.next();
            //将请求封装为UDP数据报,该数据报中包含了请求内容，目的服务器ip地址、目的端口
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIp),serverPort);
            //发送请求
            datagramSocket.send(requestPacket);
            //接收服务器响应，并解析响应内容
            byte[] buf = new byte[4096];
            DatagramPacket responsePacket = new DatagramPacket(buf,buf.length);
            datagramSocket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            //打印到主屏幕上
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
